<template>
  <el-config-provider>
    <el-container class="app_container">
      <el-header>
        <div class="d-flex justify-content-between">
          <div class="hd fw-bold">
            <div class="logo hstack">
              <img src="@/assets/img/logo.png">
            </div>
          </div>
          <!-- -->
          <div class="menu-wrapper">
            <!-- <el-icon @click="onToggleAside()">
              <Expand v-if="visibleState.aside" />
              <Fold v-else />
            </el-icon> -->
            <!-- 一级目录 -->
            <el-menu class="flex-grow-1" mode="horizontal" :default-active="activeMenuId" @select="handleSelect">
              <template v-for="(item, idx) of dataOfMenus">
                <el-menu-item :index="item.id.toString()" :class="activeMenuId==item.id?'is-active':''">{{ item.title }}</el-menu-item>
              </template>
            </el-menu>
          </div>

          <div class="d-flex align-items-center">
            <img src="@/assets/img/home.svg" alt="logo" @click="onMenuCommand('home')" class="mr-sm-4" />
            <img src="@/assets/img/logout.svg" alt="logo" @click="onMenuCommand('logout')" />
          </div>
        </div>
      </el-header>
      <el-container>
        <el-aside :width="visibleState.aside ? '160px' : '0px'" class="d-flex flex-column" v-show="visibleState.aside">
          <el-menu :default-active="activeSubMenuId" class="flex-grow-1 aside-menu" @select="handleMenu">
            <template v-for="(item, idx) of dataOfSubMenus">
              <!-- 预留三级目录 -->
              <template v-if="item.children&&item.children.length">
                <!-- 有子菜单 -->
                <el-sub-menu :index="item.id.toString()">
                  <template #title>
                    <span>{{ item.title }}</span>
                  </template>
                  <el-menu-item :index="item2.id.toString()" v-for="(item2, idx2) of item.children" :key="idx2" @click="onClickMenuItem(item2)">
                    {{ item2.title }}
                  </el-menu-item>
                </el-sub-menu>
              </template>
              <template v-else>
                <!-- 二级目录 -->
                <!-- 无子菜单 -->
                <el-menu-item :index="item.id.toString()" :disabled="userStore.user.isSupper!=1 && (item.path==='/liveExamine'||item.path=='/recordExamine')">
                  <template #title>
                    <span>{{ item.title }}</span>
                  </template>
                </el-menu-item>

              </template>

            </template>

          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>

  </el-config-provider>
</template>

<script setup>
/**
 * 布局视图组件
 */
import { onMounted, ref, inject, provide, watch, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import config from '@/config/index';
import pageEnum from '@/config/pageEnum';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsString from '@/utils/EsString';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import useAuthStore from '@/stores/useAuthStore';
import useUserStore from '@/stores/useUserStore';
import MenuTabs from '@/components/menu-tabs/MenuTabs.vue';
import MenusJson from '@/mock/modules/MenusJSON';
// ======================================================
//                      变量声明
// ======================================================
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const authStore = useAuthStore();
const dataOfMenus = ref([]);//一级目录
const dataOfSubMenus = ref([]);//二级目录
//以id问索引
const menuPathSave = ref({})
const menuIdSave = ref({})
//以当前url为索引记录信息
const menuCurPathSave = ref({})
//
const menuTabsRef = ref(null)
//横向一级目录
const activeMenuId = ref(null);
//左边二级目录
const activeSubMenuId = ref(null);
//是否显示左边aside
const visibleState = ref({
  aside: true
})
const defaultTabInfo = { id: 'startup', title: '仪表盘', path: '/index/index' };
let { home_url = "" } = route.query;
watch(() => route.path, (newPath, oldPath) => {
  nextTick(() => {
    if (newPath == pageEnum.TOURVIDEO) {
      onAsideFun(false)
    }
    if (newPath && oldPath) {
      if (oldPath == pageEnum.TOURVIDEO) {
        let _cur = menuCurPathSave.value[newPath]
        if (_cur) {
          let { pid } = menuIdSave.value[_cur.id]
          //二级目录
          if (_cur.level == 2) {
            let _menu = dataOfMenus.value.find((item) => item.id == pid)
            if (_menu.children.length && _menu.children.length > 1) {
              onAsideFun(true)
            }
          } else if (_cur.level == 3) {//三级目录
            onAsideFun(true)
          }
        }
      }


    }
  })
}, {
  immediate: true
});




// ======================================================
//                      点击操作
// ======================================================
// 点击一级目录
const handleSelect = (key) => {
  activeMenuId.value = key.toString();
  let nav = dataOfMenus.value.find((item) => item.id == key);
  loadChildMenu(nav)
};

// 点击二级目录
const handleMenu = (key) => {
  activeSubMenuId.value = key.toString();
  let nav = dataOfSubMenus.value.find((item) => item.id == key);
  console.log("二级菜单",dataOfSubMenus.value)
  if (nav) {
    console.log("拿到数据了",nav)
    onClickMenuItem(nav)
  }
};

// 点击菜单项目
const onClickMenuItem = (item) => {
  if (!item) {
    item = defaultTabInfo;
  }
  loadView(item);
}
// 为子组件提供创建标签页的方法
// 使用方法：
provide('addMenuIab', onClickMenuItem)

// 点击切换菜单命令
const onMenuCommand = (cmd) => {
  switch (cmd) {
    case 'logout':
      onLogout();
      break;
    case 'home':
      router.push('/home')
      break;
  }
}
// 点击退出登录按钮
const onLogout = () => {
  ElMessageBox.confirm('您确定要退出登录吗？', '操作确认', { confirmButtonText: '确定', cancelButtonText: '取消' }).then(res => {
    authStore.logout();
    userStore.clear();
    EsAjax.post(ApiUrls.logout)
    router.push('/login');
  })
}
// 点击切换侧边栏按钮
const onToggleAside = () => {
  visibleState.value.aside = !visibleState.value.aside
}
// 点击切换侧边栏按钮
const onAsideFun = (flag = false) => {
  visibleState.value.aside = flag
}


// ======================================================
//                      处理事件
// ======================================================


// 加载指定的视图文件
const loadView = (item) => {
  // if (item.path && item.path !== route.path) {
  if (!!item.children?.length) {
    router.push(item.children[0].path);
    activeSubMenuId.value = item.children[0].id.toString();
  } else {
    router.push(item.path);
    activeSubMenuId.value = item.id.toString();
  }
  // }
}
//加载二级菜单
const loadChildMenu = (menu, index = 0) => {
  onAsideFun(true)
  //默认二级级目录
  let child = menu?.children || []
  dataOfSubMenus.value = child
  if (child && child.length) {
    if (child.length == 1 && typeof (child.children) == 'undefined') {
      onAsideFun(false)
    }
    let chi = child[index]
    activeSubMenuId.id = chi.id.toString()
    loadView(chi)
  }
}

// 加载权限数据
const loadMenus = () => {
  return new Promise(resolve => {
    // EsAjax.post(ApiUrls.resourceUsermenu).then(res => {
    //   console.log('[INFO] BaseLayoutView 加载权限数据 res = ', res);
    //   if (res.data.code !== 200) {
    //     ElMessage.warning(res.data.msg);
    //     return;
    //   }
    let { data } = MenusJson
    // let { data } = res.data
    // console.log('data,datadatadata',data)
    let path = '', codes = [], menus = [], subMenus = [];
    data.forEach(item => {
      //一级
      menuPathSave.value[item.path] = { ...item, pid: 0 }
      menuIdSave.value[item.id] = { ...item, pid: 0 }
      subMenus = [];
      item.children.forEach((item2, idx) => {
        //二级
        menuIdSave.value[item2.id] = { ...item2, pid: item.id }
        if (!item2.hidden) {
          //三级目录
          if (item2.component === "Layout") {
            let _subMenus = { id: item2.id, title: item2?.meta?.title, children: [] }
            item2.children.forEach((item3, idx) => {
              if (idx === 0) {
                item.path = '/' + item3.path
              }
              menuIdSave.value[item3.id] = { ...item3, pid: item2.id }
              path = '/' + item3.path
              let _thrMenus = { id: item3.id, title: item3?.meta?.title, path: path, level: 3 }
              menuCurPathSave.value[path] = _thrMenus
              _subMenus.children.push(_thrMenus);
            })
            subMenus.push(_subMenus);
          } else {
            // 二级目录
            path = '/' + item2.path
            let _subMenus = { id: item2.id, title: item2?.meta?.title, path: path, level: 2 }
            menuCurPathSave.value[path] = _subMenus
            subMenus.push(_subMenus);
          }
        }
      })

      menus.push({ id: item.id, title: item?.meta?.title, path: item.path, children: subMenus });

    })
    dataOfMenus.value = menus;
    if (home_url) {
      setHomeUrl()
    } else {
      setPath()
    }
    resolve()
    // }).catch(err => {
    //   ElMessage.error('网络错误：' + err.message);
    // })
  })
}
const setHomeUrl = () => {
  if (menuPathSave.value[home_url]) {
    handleSelect(menuPathSave.value[home_url].id)
  }
}

const setPath = () => {
  if (route.path == '/') {
    //默认加载第一个路由
    let menu = dataOfMenus.value[0]
    //默认一级目录
    activeMenuId.value = menu.id.toString()
    //设置二级目录
    loadChildMenu(menu)

  } else {
    //有路由
    let _cur = menuCurPathSave.value[route.path]
    if (_cur) {
      let { pid } = menuIdSave.value[_cur.id]
      let _menuids = menuIdSave.value[pid]
      //二级目录
      if (_cur.level == 2) {
        let _menu = dataOfMenus.value.find((item) => item.id == pid)
        activeMenuId.value = pid.toString();
        var index = _menuids.children.findIndex((item) => item.id == _cur.id);
        loadChildMenu(_menu, index)
      } else if (_cur.level == 3) {//三级目录
        let _menu = dataOfMenus.value.find((item) => item.id == _menuids.pid)
        activeMenuId.value = _menuids.pid.toString();
        loadChildMenu(_menu)
        setTimeout(() => {
          activeSubMenuId.value = _cur.id.toString();
        }, 100);

      }
    }
  }
}
// ======================================================
//                      生命周期
// ======================================================

onMounted(() => {
  loadMenus().then(() => {
    // menuTabsRef.value.init(defaultTabInfo);
  });
})

</script>

<style lang="less" scoped>
.el-aside {
  border: none !important;
}

.menu-wrapper {
  display: flex;
  flex-direction: row;
  list-style: none;
  -ml-flex-align: center;
  align-items: center;
  padding: 0;
  margin: 0 40px 0 0;
  position: relative;
  min-width: 1200px;
  .menu-item {
    flex-shrink: 0;
  }
  > .menu-item + .menu-item {
    margin-left: 40px;
  }

  .menu-item-link {
    font-weight: 400;
    font-size: @text-df;
    line-height: 100px;
    cursor: pointer;
    position: relative;
    .el-icon {
      vertical-align: middle;
    }
    a {
      display: inline-block;
      color: @primary-text;
      transition: color 0.3s;

      :hover {
        color: app;
      }
    }
    .router-link-exact-active {
      font-weight: 600;
      span:after {
        content: "";
        display: block;
        height: 2px;
        position: absolute;
        width: 40px;
        left: calc(50% - 20px);
        bottom: 0px;
        background-color: @base-color;
      }
    }
  }
}

.aside-menu.el-menu--vertical:not(.el-menu--collapse):not(
    .el-menu--popup-container
  )
  .el-menu-item,
.aside-menu.el-menu--vertical:not(.el-menu--collapse):not(
    .el-menu--popup-container
  )
  .el-menu-item-group__title,
.aside-menu.el-menu--vertical:not(.el-menu--collapse):not(
    .el-menu--popup-container
  )
  .el-sub-menu__title {
  padding-left: 40px;
}

:deep(.el-menu) {
  border: none;
  background-color: transparent !important;
}
:deep(.el-menu-item.is-active) {
  color: @base-color !important;
  font-weight: bold;
}
:deep(.el-menu-item) {
  background: transparent !important;
  color: #fff;
}
:deep(.el-sub-menu) {
  background: transparent !important;
}

:deep(.el-menu-item:active) {
  background: #fff;
}
:deep(.el-menu-item:hover) {
  background: #fff;
}
:deep(.el-menu-item) {
  background: #fff;
}

.el-menu--horizontal {
  border: none;
  justify-content: flex-end;
}
.el-menu--horizontal > .el-menu-item.is-active,
.el-menu--horizontal .el-menu-item:not(.is-disabled):focus,
.el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
  background: url("../../assets/img/menuOn.svg") no-repeat center !important;
  background-size: 100% !important;
  border-bottom: none !important;
  color: #ffffff !important;
  font-weight: 400;
  // background-position: center;
}

.el-menu--horizontal > .el-menu-item {
  color: #9ba8b8;
  background: url("../../assets/img/menu.svg") no-repeat center !important;
  background-size: 100% !important;
  border-bottom: none !important;
  // background-position: center;
  padding: 0 40px;
}
// .el-menu--horizontal > .el-menu-item.is-active {
//   background: url("../../assets/img/menuOn.svg") no-repeat;
//   background-size: 100% !important;
//   background-position: center;
//   border-bottom: none !important;
//   color: #ffffff !important;
// }
</style>
